| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107 |
- import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
- import { z } from '@hono/zod-openapi';
- import { AppDataSource } from '@/server/data-source';
- import { ContactService } from '@/server/modules/contacts/contact.service';
- import { ErrorSchema } from '@/server/utils/errorHandler';
- import { authMiddleware } from '@/server/middleware/auth';
- import { logger } from '@/server/utils/logger';
- import { AuthContext } from '@/server/types/context';
- // Initialize service
- const contactService = new ContactService(AppDataSource);
- // Path parameters schema
- const ParamsSchema = z.object({
- id: z.coerce.number().int().positive().openapi({
- param: { name: 'id', in: 'path' },
- example: 1,
- description: '联系人ID'
- })
- });
- // Success response schema
- const SuccessResponseSchema = z.object({
- code: z.number().openapi({ example: 200 }),
- message: z.string().openapi({ example: '联系人删除成功' }),
- data: z.object({
- success: z.boolean().openapi({ example: true })
- })
- });
- // Route definition
- const routeDef = createRoute({
- method: 'delete',
- path: '/{id}',
- middleware: [authMiddleware],
- request: {
- params: ParamsSchema
- },
- responses: {
- 200: {
- description: '联系人删除成功',
- content: {
- 'application/json': { schema: SuccessResponseSchema }
- }
- },
- 400: {
- description: '客户端错误',
- content: { 'application/json': { schema: ErrorSchema } }
- },
- 401: {
- description: '未授权访问',
- content: { 'application/json': { schema: ErrorSchema } }
- },
- 404: {
- description: '联系人不存在',
- content: { 'application/json': { schema: ErrorSchema } }
- },
- 500: {
- description: '服务器错误',
- content: { 'application/json': { schema: ErrorSchema } }
- }
- }
- });
- // Create route instance
- const deleteRoute = new OpenAPIHono<AuthContext>().openapi(routeDef, async (c) => {
- try {
- const { id } = c.req.valid('param');
- const user = c.get('user');
-
- if (!user) {
- return c.json({
- code: 401,
- message: '未授权访问'
- }, 401);
- }
-
- logger.api(`用户 ${user.id} 删除联系人: ${id}`);
-
- // Delete contact (soft delete)
- await contactService.remove(id);
-
- return c.json({
- code: 200,
- message: '联系人删除成功',
- data: { success: true }
- }, 200);
- } catch (err) {
- const error = err as Error;
- logger.error('删除联系人失败:', error);
-
- // Check if error is "contact not found"
- if (error.message === '联系人不存在') {
- return c.json({
- code: 404,
- message: error.message
- }, 404);
- }
-
- return c.json({
- code: 500,
- message: error.message || '删除联系人失败'
- }, 500);
- }
- });
- export default deleteRoute;
|